#include "common_util.h"
#include <Arduino.h>
#include <WiFiManager.h>  // https://github.com/tzapu/WiFiManager
#include <nvs_flash.h>

// 广播
void broadcast(String data) {
  Serial.println(data);
  for (uint8_t i = 0; i < MAX_TCP_CLIENTS; i++) {
    if (serverClients[i] && serverClients[i].connected()) {
      serverClients[i].println(data);
    }
  }
  if (tcp_client.connected()) {
    tcp_client.println(data);
  }
}

uint8_t requestTest(String request) {
  if (request.length() <= 0 || request.length() >= 100) {
    return 0;
  }
  if (request.length() == 1 && (request.charAt(0) == '\n' || request.charAt(0) == '\r')) {
    return 0;
  }
  return 1;
}

void saveVlaueU8(char* key, uint8_t value) {
  nvs_flash_init();
  nvs_open(nvs_space, NVS_READWRITE, &my_nvs_handle_t);
  nvs_set_u8(my_nvs_handle_t, key, value);
  nvs_close(my_nvs_handle_t);
  nvs_flash_deinit();
}

void saveVlaueU16(char* key, uint16_t value) {
  nvs_flash_init();
  nvs_open(nvs_space, NVS_READWRITE, &my_nvs_handle_t);
  nvs_set_u16(my_nvs_handle_t, key, value);
  nvs_close(my_nvs_handle_t);
  nvs_flash_deinit();
}

void saveVlaueU32(char* key, uint32_t value) {
  nvs_flash_init();
  nvs_open(nvs_space, NVS_READWRITE, &my_nvs_handle_t);
  nvs_set_u32(my_nvs_handle_t, key, value);
  nvs_close(my_nvs_handle_t);
  nvs_flash_deinit();
}

void saveVlaueStr(char* key, char* value) {
  nvs_flash_init();
  nvs_open(nvs_space, NVS_READWRITE, &my_nvs_handle_t);
  nvs_set_str(my_nvs_handle_t, key, value);
  nvs_close(my_nvs_handle_t);
  nvs_flash_deinit();
}

uint8_t s2h(char c) {
  if (c >= '0' && c <= '9') {
    return c - '0';
  }
  if (c >= 'A' && c <= 'F') {
    return (c - 'A') + 10;
  }
  if (c >= 'a' && c <= 'f') {
    return (c - 'a') + 10;
  }
  return 0;
}

char t2h(uint8_t i) {
  if (i >= 0 && i <= 9) {
    return i + '0';
  }
  switch (i) {
    case 10:
      return 'A';
    case 11:
      return 'B';
    case 12:
      return 'C';
    case 13:
      return 'D';
    case 14:
      return 'E';
    case 15:
      return 'F';
  }
  return '0';
}